<?php
include 'vendor/autoload.php';

use Sabre\Event\Emitter;
use Sabre\Event\Loop;
use Sabre\Event;

$emitter = new Emitter();

// Subscribing
$emitter->on('create', function($index) {

	echo file_get_contents('http://localhost/demo.php?index='.$index);
	echo "\n";
});

// Publishing
// foreach(range(1,10) as $k=>$v){
	// $emitter->emit('create',[$v]);
// }


// $intervalId = Loop\setInterval(function() {

    // echo "Hello\n";

// }, 1);

// Loop\nextTick(function() {
    // echo "Hello\n";
// });

// Loop\nextTick(function() {
    // echo file_get_contents('http://localhost/demo.php?index=100');
	// echo "\n";
// });

// Loop\nextTick(function() {
    // echo file_get_contents('http://localhost/demo.php?index=200');
	// echo "\n";
// });

echo "666\n";


Loop\run();


// Event\coroutine(function() {

    // try {

        // $result = yield file_get_contents('http://localhost/demo.php?index=1');
		// echo $result;
        // $result = yield file_get_contents('http://localhost/demo.php?index=2');
		// echo $result;
        // $result = yield file_get_contents('http://localhost/demo.php?index=3');
        // echo $result;

    // } catch (\Exception $reason) {

        // echo $reason;

    // }

// });



function anotherAsyncOperation1(){
	return new Sabre\Event\Promise(function($a){
		$fun=$a[1];
		$result=file_get_contents('http://localhost/demo.php?index=1');
		$a[0]->$fun($result);
	});
}
function anotherAsyncOperation2(){
	return new Sabre\Event\Promise(function($a){
		$fun=$a[1];
		$result=file_get_contents('http://localhost/demo.php?index=2');
		$a[0]->$fun($result);
	});
}
function anotherAsyncOperation3(){
	return new Sabre\Event\Promise(function($a){
		$fun=$a[1];
		$result=file_get_contents('http://localhost/demo.php?index=3');
		$a[0]->$fun($result);
	});
}

// $promise1=anotherAsyncOperation1();
// $promise2=anotherAsyncOperation2();
// $promise3=anotherAsyncOperation3();


// $data=Sabre\Event\Promise\all([$promise1,$promise2,$promise3])->wait();
// print_r($data);

Event\coroutine(function() {

    try {

        $result = yield anotherAsyncOperation1();
		echo $result;
		echo "\n";
        $result = yield anotherAsyncOperation2();
		echo $result;
		echo "\n";
        $result = yield anotherAsyncOperation3();
        echo $result;
		echo "\n";

    } catch (\Exception $reason) {

        echo $reason;

    }

})->wait();